<?php

namespace app\adminapi\controller;

use think\Controller;
use think\Request;
use app\common\model\Type as TypeModel;

class Type extends BaseApi
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $list = TypeModel::select();
        $this->ok($list);
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        //
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        //
        $params = input();
        //参数检测
        $validate = $this->validate($params,[
            'type_name|模型名称'=>'require|max:20',
            'spec|规格'=>'require',
            'attr|属性'=>'require',
        ]);
        if ($validate !== true){
            $this->fail($validate);
        }
        //开启事务
        \think\Db::startTrans();
        try {
            //添加模型数据
            $type = TypeModel::create($params,true);
            // $type = TypeModel::create(['type_name'=>$params['type_name]],true);
            //添加规格名称数据 去空，没有规格值得去掉
            //去除空的规格值和空的规格名
            foreach ($params['spec'] as $key=>$spec){
                //判断规格名是否为空
                if (empty(trim($spec['name']))){
                    unset($params['spec'][$key]);
                    continue;
                }
                foreach ($spec['value'] as $k=>$value){
                    if (empty(trim($value))){
                        unset($params['spec'][$key][$value][$k]);
                    }
                }
                //判断规格值是否是空数组
               if(empty($spec['value'])){
                   unset($params['spec'][$key]);
               }
            }

            foreach ($params['spec'] as $spec){
                $data_spec[] = ['type_name'=>$spec['name'],'sort'=>$spec['sort']];
            }
            $spec_model = new \app\common\model\Spec;
            $spec_data = $spec_model->allowField(true)->saveAll($data_spec); //返回一个多维数组[['id'][]]

            //添加规格值数据
            $data_spec_value = [];
            foreach ($params['spec'] as $kk=>$spec_v){
                foreach ($spec_v['value'] as $vv){
                    $data_spec_value[] =['type_id'=>$type['id'],'spec_id'=>$spec_data[$kk]['id'],'spec_value'=>$vv];
                }
            }
            $spec_value_model = new app\common\model\SpecValue;
            $spec_value_model->saveAll($data_spec_value);
            //添加属性数据 去空，没有属性名的数据
            foreach ($params['attr'] as $k=>$attr){
                if (empty(trim($attr['name']))){
                    unset($params['attr'][$k]);
                    continue;
                }
                foreach ($attr['value'] as $i=>$value){
                    if (empty(trim($value))){
                        unset($params['attr'][$k]['value'][$i]);
                    }
                }
                if (empty($attr['value'])){
                    unset($params[$k]);
                }
            }
            $data_save_attr = [];
            foreach ($params['attr'] as $k => $v){
                $data_save_attr[]=['type_id'=>$type['id'],'attr_value'=>implode(',',$v),'sort'=>$v['sort'],'attr_name'=>$v['attr_name']];
            }
            $attr_model = new app\common\model\Attribute;
            $attr_model->saveAll($data_save_attr);
            \think\Db::commit();

        }catch (\Exception $e){
            \think\Db::rollback();
            $this->fail('添加失败');
        }
        $this->ok();
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        $info = TypeModel::with('specs,specs.spec_values,attrs')->find($id);
        $this->ok($info);
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //判断是否有商品在使用规格
        $goods = \app\common\model\Goods::where('type_id',$id)->count();
        if ($goods>0){
            $this->fail('有商品已经使用了，不能删除');
        }
        //删除数据，规格名，规格名，属性
        //事务
        \think\Db::startTrans();
        try {
            TypeModel::destroy($id);
            \app\common\model\Spec::where('type_id',$id)->delete();
            \app\common\model\SpecValue::destroy(['type_id'=>$id]);
            \app\common\model\Attribute::destroy(['type_id'=>$id]);
        }catch (\Exception $e) {
            //回滚事务
            \think\Db::rollback();
            $msg = $e->getMessage();
            $this->fail('删除失败');
        }
        $this->ok();
    }
}
